package sample.login;

import com.alibaba.fastjson.JSON;
import com.google.common.io.Files;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import lombok.SneakyThrows;
import sample.Main;
import sample.constants.FilesIndexConstants;
import sample.login.service.LoginService;
import sample.main.view.MainPageFxmlView;
import sample.register.view.RegisterFxmlView;
import sample.utils.FileUtils;
import sample.utils.ResultBody;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;

/**
 * @author taowenchen
 */
@FXMLController
public class LoginController implements Initializable {

    @Resource
    LoginService loginService;

    @Resource
    RegisterFxmlView registerFxmlView;
    @Resource
    MainPageFxmlView mainPageFxmlView;


    @FXML
    private PasswordField password;

    @FXML
    private TextField account;

    @FXML
    Label errorMsg;

    @FXML
    void register(ActionEvent event) {
        Main.getScene().setRoot(registerFxmlView.getView());
    }


    @FXML
    void login(ActionEvent event) {
        errorMsg.setOpacity(0);


        final ResultBody login = loginService.login(User.builder().account(account.getText()).password(password.getText()).build());
        if (login.isStatus()) {
            Main.getScene().setRoot(mainPageFxmlView.getView());
            return;
        }

        errorMsg.setText(login.getMsg());
        errorMsg.setTextFill(Color.RED);
        errorMsg.setOpacity(1);
    }


    @SneakyThrows
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        final File lastLoginFile = new File(FileUtils.getFile() + String.format(FilesIndexConstants.ACCOUNT_FILE_DIR, "lastlogin.dat"));
        if (lastLoginFile.exists()) {
            final String userJsonString = Files.readFirstLine(lastLoginFile, StandardCharsets.UTF_8);
            User user = JSON.parseObject(userJsonString, User.class);
            account.setText(user.getAccount());
            password.setText(user.getPassword());
        }

    }
}
